<template>
  <ATable :size="model.size" :bordered="model.bordered" :columns="columns" :rowSelection="model.rowSelection"
          :pagination="model.pagination" :data-source="source" rowKey="id" :loading="loading" class="ivz-preview-table">
    <template #action="{record}">
      <ATag v-for="meta in tableFunMetas" :key="meta.func" @click="() => funcHandle(meta, record)" class="lcd-ol-tag" color="#87d068">{{meta.name}}</ATag>
    </template>
  </ATable>
</template>

<script>
import {mapGetters, useStore} from "vuex";
import {inject, ref} from "vue";
import Preview from "./index.js";

export default {
  name: "IvzPreviewTable",
  setup(props) {
    let store = useStore();
    let meta = store.getters['tableMeta'];
    let model = meta.tabModel
    let loading = ref(false);
    let source = ref([]);
    let context = inject(Preview.PreviewProvideContext);
    return {model, loading, source, context}
  },
  computed: {
    ...mapGetters(['tableMeta', 'tableMetas', 'tableFunMetas', 'preview']),
    columns() {
      return this.tableMetas.map(item => item.tabModel);
    }
  },
  created() {
    this.context.query = (model) => {
      this.loading = true;
      this.$http.get("/preview/view", model).then(resp => {
        if(resp.code == 200) {
          this.source = resp.data['records'];
          this.model.pagination.total = resp.data.total;
        } else {
          this.$msg.warningMessage(resp.message);
        }
      }).catch(reason => console.warn(reason))
          .finally(() => this.loading = false)
    }
  },
  methods: {
    funcHandle(meta, record) {
      let func = meta.func;
      if(func == 'edit') {
        this.preview.editVisible = true;
        this.context.getById(record.id);

      } else if(func == 'del') {
        this.$msg.confirmOfWaiting(`确定删除记录`, "删除之后将不能恢复", () => {
          return new Promise((resolve, reject) => {
            this.$http.post("/preview/del", [record.id]).then(resp => {
              if(resp.code == 200) {
                this.$msg.successMessage("删除记录成功");
                this.context.query();
              } else {
                this.$msg.warningMessage(resp.message)
              }
            }).finally(() => resolve())
          })
        });
      } else {
        this.$msg.warningMessage("不支持模拟此操作")
      }
    }
  }
}
</script>

<style scoped>
.ivz-preview-table {
  margin: 8px 0px 0px;
}
.ivz-preview-table .lcd-ol-tag {
  cursor: pointer;
}
</style>